package com.ning.activitys.skysound.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.ning.activitys.skysound.base.MyApplication;
import com.ning.activitys.skysound.beans.GsonMusicListDetails;
import com.ning.activitys.skysound.beans.GsonRadioDetails;
import com.ning.activitys.skysound.beans.MusicDetailsBeans;
import com.ning.activitys.skysound.beans.SongBeans;
import com.ning.activitys.skysound.datas.MusicDetailsTool;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * Created by dllo on 16/1/11.
 */
public class PlayService extends Service implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {

    private boolean isPause = false;

    private MediaPlayer mediaPlayer;
    private int currentPlayPosition; //当前正在播放第几首歌
    private List<MusicDetailsBeans> musicDetailsData;
    private MusicUpDataListener musicUpDataListener;
    private MyApplication myApplication;
    private int netPosition = 0;


    private GsonRadioDetails gsonRadioDetails;

    public GsonRadioDetails getGsonRadioDetails() {
        return gsonRadioDetails;
    }

    public void setGsonRadioDetails(GsonRadioDetails gsonRadioDetails) {
        this.gsonRadioDetails = gsonRadioDetails;
    }

    private GsonMusicListDetails gsonMusicListDetails;

    public GsonMusicListDetails getGsonMusicListDetails() {
        return gsonMusicListDetails;
    }

    public void setGsonMusicListDetails(GsonMusicListDetails gsonMusicListDetails) {
        this.gsonMusicListDetails = gsonMusicListDetails;
    }

    private String netSongUrl;

    private SongBeans netSongBeans = new SongBeans();

    public SongBeans getNetSongBeans() {
        return netSongBeans;
    }

    public void setNetSongBeans(SongBeans netSongBeans) {
        this.netSongBeans = netSongBeans;
    }

    public static int IS_NET_MUSIC = 1; //是否是网络音乐 0是 1不是



    //创建线程池,种类按顺序执行
    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    public static final int ORDER_PLAY = 1;
    public static final int RANDOM_PLAY = 2;
    public static final int SINGLE_PLAY = 3;
    private int play_mode = ORDER_PLAY;

    public static final int ALL_MUSIC = 1;
    public static final int LIKE_MUSIC = 2;
    public static final int RECENT_MISIC = 3;
    private int platList = ALL_MUSIC;

    public static final int RADIO_TYPE = 1;
    public static final int MUSIC_LIST_TYPR = 2;
    public static final int RANKING_TYPE = 3;
    public static final int SINGER_TYPE = 4;
    private  int SkySoundListType = RADIO_TYPE;

    public int getSkySoundListType() {
        return SkySoundListType;
    }

    public void setSkySoundListType(int skySoundListType) {
        SkySoundListType = skySoundListType;
    }

    /**
     * 播放模式的标签 设置,获取
     * */
    public int getPlay_mode() {
        return play_mode;
    }

    public void setPlay_mode(int play_mode) {
        this.play_mode = play_mode;
    }

    /**
     *  播放列表的标签 设置,获取
     */
    public int getPlatList() {
        return platList;
    }
    public void setPlatList(int platList) {
        this.platList = platList;
    }


    @Nullable
    @Override
    public void onCreate() {
        super.onCreate();

        /**
         * 从SharedPreferences 中获取上次退出储存的数据
         * */
        myApplication = (MyApplication) getApplication();
        currentPlayPosition = myApplication.sharedPreferences.getInt("currentPlayPosition",0);
        play_mode = myApplication.sharedPreferences.getInt("play_mode", 1);

        mediaPlayer = new MediaPlayer();
        //改变播放列表

        musicDetailsData = MusicDetailsTool.getMusicDetails(this);

        executorService.execute(updateStartRunnable);

        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnErrorListener(this);
    }


    Runnable updateStartRunnable = new Runnable() {
        @Override
        public void run() {
            while (true){
                if (musicUpDataListener != null && mediaPlayer != null && mediaPlayer.isPlaying()){
                    //更行进度条
                    musicUpDataListener.onPublish(getCurrentProgress());
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };


    @Override
    public void onDestroy() {
        super.onDestroy();

        //回收线程池
        if (executorService != null && !executorService.isShutdown()){
            executorService.shutdown();
            executorService = null;
        }
    }


    //原来是在上面定义,直接返回MyBind 对象
    @Override
    public IBinder onBind(Intent intent) {
        return new PlayBind();
    }

    /**
     * 播放完成的监听
     * */
    Random random = new Random();
    @Override
    public void onCompletion(MediaPlayer mp) {
        switch (play_mode){
            case ORDER_PLAY:

                next();
                break;
            case RANDOM_PLAY:
                if (IS_NET_MUSIC == 1){

                    int rd = random.nextInt(musicDetailsData.size());
                    play(rd);

                }else if (IS_NET_MUSIC == 0){

                    if (SkySoundListType == RADIO_TYPE) {
                        int netRd = random.nextInt(gsonRadioDetails.getData().size());

                        playNet(gsonRadioDetails.getData().get(netRd).getUrl_list().get(0).getUrl(), netRd);

                    }else if (SkySoundListType == MUSIC_LIST_TYPR){
                        int netRd = random.nextInt(gsonMusicListDetails.getSongs().size());
                        playNet(gsonMusicListDetails.getSongs().get(netRd).getUrlList().get(0).getUrl(), netRd);

                    }
                }

                break;
            case SINGLE_PLAY:
                if (IS_NET_MUSIC == 1){

                    play(currentPlayPosition);

                }else if (IS_NET_MUSIC == 0){

                    if (SkySoundListType == RADIO_TYPE) {
                        playNet(gsonRadioDetails.getData().get(getNetSongPosition()).getUrl_list().get(0).getUrl(), netPosition);
                    }else if (SkySoundListType == MUSIC_LIST_TYPR){

                        playNet(gsonMusicListDetails.getSongs().get(netPosition).getUrlList().get(0).getUrl(), netPosition);
                    }
                }


                break;

            default:
                break;
        }

    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        mp.reset();
        return false;
    }

    //当调用onBind 方法就会返回得到PlayBind 对象,
    // 通过返回的PlayBind 对象就可使用 PlayBind 里面的 getPlayService 的方法,
    // 然后通过这个方法就可以获得PlayService 的对象

    //Bind 类 里面写了一个获得PlayService 对象的方法
    public class PlayBind extends Binder{
        public PlayService getPlayService(){
            return PlayService.this;
        }
    }

    //播放
    public void play(int position){

        if (position >= 0 && position < musicDetailsData.size()){

            MusicDetailsBeans musicDetails = musicDetailsData.get(position);

            try {
                //从新播放
                mediaPlayer.reset();
                //设置来源
                mediaPlayer.setDataSource(this, Uri.parse(musicDetails.getUrl()));

                mediaPlayer.prepare();

                mediaPlayer.start();

                currentPlayPosition = position;
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (musicUpDataListener != null){

                musicUpDataListener.onChange(currentPlayPosition);

            }

            isPause = true;

        }
    }


    public void playNet(final String url,int netPosition){

        this.netPosition = netPosition;

        this.netSongUrl = url;


        if (null != gsonRadioDetails && SkySoundListType == RADIO_TYPE) {

            //songBeans = gsonRadioDetails.getData().get(getNetSongPosition());
            netSongBeans.setTitle(gsonRadioDetails.getData().get(netPosition).getSong_name());
            netSongBeans.setSingerName(gsonRadioDetails.getData().get(netPosition).getSinger_name());
            netSongBeans.setDuration(MusicDetailsTool.getIntTime(gsonRadioDetails.getData().get(netPosition).getUrl_list().get(0).getDuration()));
        }

        if (null != gsonMusicListDetails && SkySoundListType == MUSIC_LIST_TYPR){

            netSongBeans.setTitle(gsonMusicListDetails.getSongs().get(netPosition).getName());
            netSongBeans.setSingerName(gsonMusicListDetails.getSongs().get(netPosition).getSingerName());
            netSongBeans.setDuration(gsonMusicListDetails.getSongs().get(netPosition).getAuditionList().get(0).getDuration());
        }
                try {
                    mediaPlayer.reset();

                    mediaPlayer.setDataSource(PlayService.this, Uri.parse(url));

                    mediaPlayer.prepare();

                    mediaPlayer.start();

                } catch (IOException e) {
                    e.printStackTrace();
                }


        if (musicUpDataListener != null){

            musicUpDataListener.onChange(currentPlayPosition);

        }

    }






    /**
     * 本地音乐信息 musicDetailsData的 get set 方法
     *
     * */
    public List<MusicDetailsBeans> getMusicDetailsData() {
        return musicDetailsData;
    }

    public void setMusicDetailsData(List<MusicDetailsBeans> musicDetailsData) {
        this.musicDetailsData = musicDetailsData;
    }


    /**
     *  播放控制
     *
     * */
    //暂停
    public void pause(){
        if (mediaPlayer.isPlaying()){
            mediaPlayer.pause();

            isPause = true;
        }
    }

    //上一首
    public void last() {

        if (IS_NET_MUSIC == 1) {

            if (currentPlayPosition - 1 < 0) {
                currentPlayPosition = musicDetailsData.size() - 1;
            } else {
                currentPlayPosition--;
            }
            play(currentPlayPosition);
        }else if (IS_NET_MUSIC == 0){

            if (null != netSongUrl && SkySoundListType == RADIO_TYPE) {

                if (getNetSongPosition() > 0) {

                    netPosition = getNetSongPosition() -1;
                    playNet(gsonRadioDetails.getData().get(getNetSongPosition() - 1).getUrl_list().get(0).getUrl(), netPosition);
                } else {

                    playNet(gsonRadioDetails.getData().get(getNetSongPosition()).getUrl_list().get(0).getUrl(), netPosition);
                }
            }

                if (null != gsonMusicListDetails && SkySoundListType == MUSIC_LIST_TYPR){

                    if (netPosition > 0) {

                        netPosition--;
                        playNet(gsonMusicListDetails.getSongs().get(netPosition).getUrlList().get(0).getUrl(), netPosition);

                    }else {

                        playNet(gsonMusicListDetails.getSongs().get(0).getUrlList().get(0).getUrl(), netPosition);
                    }
                }
        }
    }

    //下一首
    public void next(){

        if (IS_NET_MUSIC == 1) {

            if (currentPlayPosition + 1 > musicDetailsData.size() - 1) {
                currentPlayPosition = 0;
            } else {
                currentPlayPosition++;
            }
            play(currentPlayPosition);

        }else if (IS_NET_MUSIC == 0){

            if (null != netSongUrl && null != gsonRadioDetails && SkySoundListType == RADIO_TYPE){

                netPosition = getNetSongPosition() +1;

                playNet(gsonRadioDetails.getData().get(getNetSongPosition() + 1).getUrl_list().get(0).getUrl(),netPosition);

            }else if (null != gsonMusicListDetails && SkySoundListType == MUSIC_LIST_TYPR){

                netPosition++;
                playNet(gsonMusicListDetails.getSongs().get(netPosition).getUrlList().get(0).getUrl(),netPosition);
            }
        }
    }


    /**
     *  获取当前正在播放的网络歌曲的位置
     * */
    private int getNetSongPosition() {

        for (int i = 0; i < gsonRadioDetails.getData().size(); i++) {

            if (netSongUrl.equals(gsonRadioDetails.getData().get(i).getUrl_list().get(0).getUrl())) {

                return i;
            }
        }
        return 0;
    }

    //开始
    public void start(){
        if (mediaPlayer != null && !mediaPlayer.isPlaying()){
            mediaPlayer.start();
            isPause = false;
        }
    }

    //判断是否正在播放
    public boolean isPlay(){
        if (mediaPlayer.isPlaying()){
            return true;
        }
        return false;
    }

    //判断是否是暂停
    public boolean isPause(){
        return isPause;
    }

    //获取当前正在播放的进度
    public int getCurrentProgress(){
        if (mediaPlayer != null && mediaPlayer.isPlaying()){
            return mediaPlayer.getCurrentPosition();

        }
        return 0;
    }

    public int getCurrentPlayPosition(){
        return currentPlayPosition;
    }

    //获取歌曲总时间
    public int getDuration(){

       return mediaPlayer.getDuration();
    }

    //跳到当前播放歌曲的某个时间
    public void seekTo(int msec){
         mediaPlayer.seekTo(msec);
    }



    //更新状态的接口
    public interface MusicUpDataListener{

        //当前播放进度
        void onPublish(int progress);
        //切换歌曲位置
        void onChange(int position);
    }

    public void setMusicUpDataListener(MusicUpDataListener musicUpDataListener) {
        this.musicUpDataListener = musicUpDataListener;

    }
}
